#include "parser.h"
#include <stdlib.h>
#include <string.h>

char ** parser(char *string, int *n, char token) {
	char **retorno;
	int i,j,k;
	int token_count=0;
	int char_count=0;
	char buffer[200];

	string = normalizeString(string);

	for(i=0;string[i] != '\0';i++) {
		if(string[i] == token) {
			token_count++;
		}
		char_count++;
	}

	retorno = (char **)malloc((token_count+1)*sizeof(char *));

	j=0;
	k=0;
	for(i=0;string[i] != '\0';i++) {
		if(string[i] != token && string[i] != '\0') {
			buffer[j++] = string[i];
		} else {
			buffer[j] = '\0';
			retorno[k] = (char *)malloc((j+1)*sizeof(char));
			strcpy(retorno[k],buffer);
			k++;
			j = 0;
		}
	}
	buffer[j] = '\0';
	retorno[k] = (char *)malloc((j+1)*sizeof(char));
	strcpy(retorno[k],buffer);
	k++;
	if(n != NULL)
		*n = k;
	return retorno;
}

char * normalizeString(char *string) {

	char *retorno;
	int n = strlen(string);
	int i,j;

	retorno = (char *)malloc((n+1)*sizeof(char));

	j=0;

	if(string[0] != ' ') {
		retorno[j++] = string[0];
	}

	i=1;
	while(i < n+1) {
		if(string[i] != ' ') {
			retorno[j++] = string[i];
		} else {
			if(string[i-1] != ' ') {
				retorno[j++] = string[i];
			}
		}
	i++;
	}

	return retorno;
}
